package com.ktjiaoyu.server.config.security;

import com.ktjiaoyu.server.pojo.Menu;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.service.IMenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Resource
    IMenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //判断当前访问的资源所需要的角色是什么
        //1.获取当前访问资源的请求路劲
        String url = ((FilterInvocation) o).getRequestUrl();
        //2.判断该资源是不是只要登录就可以；或者登录还需要拥有对应的角色
        List<Menu> list = menuService.getMenusWithRole();

        AntPathMatcher antPathMatcher=new AntPathMatcher();
        for (Menu menu : list) {
            if(antPathMatcher.match(url,menu.getUrl())){
                List<String> roleNames=new ArrayList<>();
                for (Role role : menu.getRoles()) {
                    roleNames.add(role.getName());
                }
                //登录还不够还需要拥有对应的角色
                return SecurityConfig.createList(
                        roleNames.toArray(new String[roleNames.size()]));
            }
        }
        //只要登录就可以
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
